<template>
  <div>
    <el-card class="search-card">
      <BasicTableForm
        ref="formData"
        :colNumOfRow="4"
        :formColumns="formItemList"
        :dataSource="formData"
        :defaultExpandStatus="false"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
      />
    </el-card>
    <el-card class="table-card">
      <basic-table
        showActionCol
        :showSelectCol="false"
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :tableHeight="460"
        :actionColWidth="240"
        :actionRender="renderTableBtnAction"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange"
      >
        <el-row slot="content_context" type="flex" justify="start">
          <BtnRender :render="renderBtnsBar" />
        </el-row>
      </basic-table>
    </el-card>
    <ConvertSupplierDialog
      ref="convertSupplierDialog"
      :convertType="convertType"
      :supplier="supplier"
      :isReport="true"
      :dialogVisible="dialogVisible"
      @handleSubmit="handleDialogSubmit"
      @handleClose="handleDialogClose"
    />
    <CancelReport
      :cancelVisable.sync="cancelVisable"
      :planData="planData"
      @getTableData="getTableData"
    />
  </div>
</template>
<script>
import BasicTableForm from '@/components/supplier/BasicForm';
import BasicTable from '@/components/supplier/BasicTable';
import CancelReport from './components/CancelReport'
import { FORM_ITEM_LIST, initTableColumns } from './constants';
import { getBtnsId } from '@/libs/btnsPermission';
import BasicPage from '@/mixins/supplier/basicPage';
import Dict from '@/mixins/supplier/dict';
import {
  queryInspectReportService,
  exportInspectReportService,
  cancelInspectReportService
} from '@api/supplier/returnVisteManage';
import { createExcelByExport } from '@/utils/bizUtils';
import { getBtnsBar, getTableAction } from '@supplier/utils/btnsUtils';
import BtnRender from '@/components/JSXRender/BtnRender';
import { INSPECTION_TARGET_OPTIONS } from '@/pages/supplier/constants/common';
import ConvertSupplierDialog from '@/pages/supplier/components/convertSupplierDialog'; // 转化弹窗
import { demoteSupplier } from '@/api/supplier/management/common';
import { supplierPreConvertCheck } from '@/api/supplier/components';
import { getWorkflowJumpUrl } from '@/api/supplier/workflow';

export default {
  mixins: [BasicPage, Dict], // 分页数据及方法 表单基础方法
  components: {
    BasicTableForm,
    BasicTable,
    ConvertSupplierDialog,
    CancelReport,
    BtnRender
  },
  data () {
    return {
      formItemList: FORM_ITEM_LIST,
      tableInfo: {
        list: [],
        columns: initTableColumns(this),
        loading: false
      },
      formData: {
        planCode: '', // 计划编号
        planName: '', // 计划名称
        supplierCode: '', // 供应商代码
        supplierName: '', // 供应商名称
        visitTime: [], // 拜访时间
        inspector: '', // 考察人
        inspectCompleteTime: [], // 考察完成时间
        reportTime: [], // 报告录入时间
        status: '', // 审批状态
        subsequentBacklog: '', // 待办类型
        backlogState: '', // 待办状态
        supplierClassify: '', // 供应商分类
        inspectionClassify: '', // 考察分类
        callbackTime: [], // 审批完成时间
      },
      dialogVisible: false,
      convertType: '1',
      supplier: {},
      planData: {},
      cancelVisable: false
    };
  },
  created () {
    this.getTableData();
  },
  computed: {
    isTodo () {
      return this.formData.subsequentBacklog
    }
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const btnsBar = [];
      if (this.supplierExportConfig.returnViste) {
        btnsBar.unshift({
          label: '导出',
          method: this.handleExport,
          loading: this.exportLoading,
          size: 'mini',
          type: 'primary',
          hasAuth: true
        })
      }
      return getBtnsBar(h, btnsBar, this.showBtn);
    },
    /* 状态 状态 1 待提交(暂存 位录入) 10：审核中，20：审核通过，30：审核驳回, 40: 撤回
    渲染表格操作栏按钮
      1、审批状态：待提交、审批中、审批通过、审批驳回
      2、待提交的操作按钮：录入考察报告
      3、审批中的操作按钮：查看计划、查看报告
      4、审批通过的操作按钮：查看计划、查看报告
      5、审批驳回的操作按钮：编辑报告
    1:潜在转合格, 2:合格转潜在, 3:潜在转线索, 4:供应商淘汰, 5:供应商拉黑, 6:修改资质 */
    renderTableBtnAction (h, { row }) {
      const actions = [
        { label: '查看计划', method: () => { this.viewPlan(row, 1) }, status: [10, 20] },
        { label: '查看报告', method: () => { this.viewReport(row, 1) }, status: [10, 20] },
        { label: '编辑', method: this.eidtReport, hasAuth: true, status: [30, 40] },
        { label: '录入考察报告', method: () => { this.addReport(row, 1) }, hasAuth: true, status: [1] },
        { label: '审批流', method: () => { this.handleViewApprovalFlow(row.requestId) }, hasAuth: true, status: [10, 20, 30], disabled: !row.requestId },
        { label: '取回', method: this.handleWithdraw, hasAuth: true, status: [10, 20, 30], disabled: !row.requestId },
        { label: '取消供应商考察', method: this.handleCancel, hasAuth: true, status: [1] },
      ]
      // 待办操作项
      const todoActions = [
        { label: '转合格', authLabel: '转为合格', method: () => { this.handleConvertSuppliers(row, 'qualified') }, hasAuth: true, status: '1' },
        { label: '转潜在', authLabel: '转为潜在', method: () => { this.handleConvertSuppliers(row, '5') }, hasAuth: true, status: '2' },
        { label: '转线索', authLabel: '转为线索', method: () => { this.handleConvertSuppliers(row, '3') }, hasAuth: true, status: '3' },
        { label: '淘汰供应商', method: () => { this.handleEliminateSuppliers(row, '10') }, hasAuth: true, status: '4' },
        { label: '拉黑供应商', method: () => { this.handleBlackSuppliers(row, '20') }, hasAuth: true, status: '5' },
        { label: '维护资质', method: () => { this.skipToQualificationEditPage(row) }, hasAuth: true, status: '6' },
      ]
      if (row.status == 20 && this.isTodo) {
        const actionFixList = actions.filter(item => item.status.includes(row.status))
        const actionsTodoList = todoActions.filter(item => row.subsequentBacklog.includes(item.status))
        return getTableAction({ h, row, actionList: [...actionFixList, ...actionsTodoList], showBtn: this.showBtn })
      }
      const actionList = actions.filter(item => item.status.includes(row.status))
      return getTableAction({ h, row, actionList, showBtn: this.showBtn })
    },
    // 初始化查询条件
    initSearchParams () {
      const { subsequentBacklog, backlogState } = this.$route.query;
      this.formData.subsequentBacklog = subsequentBacklog;
      this.formData.backlogState = backlogState;
      const {
        visitTime = [],
        inspectCompleteTime = [],
        reportTime = [],
        callbackTime = []
      } = this.formData
      const [ visitTimeStart, visitTimeEnd ] = visitTime
      const [ inspectCompleteTimeStart, inspectCompleteTimeEnd ] = inspectCompleteTime || []
      const [ reportTimeStart, reportTimeEnd ] = reportTime || []
      const [ callbackTimeStart, callbackTimeEnd ] = callbackTime || []
      return _.omit({
        ...this.formData,
        visitTimeStart,
        visitTimeEnd,
        inspectCompleteTimeStart,
        inspectCompleteTimeEnd,
        reportTimeStart,
        reportTimeEnd,
        callbackTimeStart,
        callbackTimeEnd,
      }, 'visitTime', 'inspectCompleteTime', 'reportTime', 'callbackTime')
    },
    // 获取表格数据
    async getTableData () {
      sessionStorage.setItem('buttonId', getBtnsId('查询'));
      const res = await queryInspectReportService(
        {
          ...this.initSearchParams(),
          ...this.pagination
        },
        state => { this.tableInfo.loading = state }
      )
      if (res) {
        const { records, total } = res.result;
        records.forEach((item) => {
          let targetNameList = [];
          INSPECTION_TARGET_OPTIONS.forEach((ele) => {
            if (item.targetList.includes(ele.value)) {
              targetNameList.push(ele.label);
            }
          })
          item.target = targetNameList.join(',')
        })
        this.tableInfo.list = records;
        this.pagination.total = total;
      }
    },
    // 导出
    async handleExport () {
      const res = await exportInspectReportService(
        this.initSearchParams(),
        state => { this.exportLoading = state }
      )
      if (res) {
        createExcelByExport({ excelTitle: '考察报告', res })
      }
    },
    // 编辑报告
    eidtReport (row) {
      const { planId, supplierId, targetList, supplierClassify } = row;
      this.$router.push({
        name: 'addReport',
        query: { planId, supplierId, targetList, supplierClassify }
      })
    },
    // 录入报告
    addReport (row) {
      const { planId, supplierId, targetList, supplierClassify } = row;
      this.$router.push({
        name: 'addReport',
        query: { planId, supplierId, targetList, supplierClassify }
      })
    },
    // 查看计划
    viewPlan (row) {
      this.$router.push({
        name: 'viewPlan',
        query: { id: row.planId, type: 'view' }
      })
    },
    // 查看报告
    viewReport (row) {
      const { planId, supplierId, targetList } = row;
      this.$router.push({
        name: 'viewReport',
        query: { planId, supplierId, targetList }
      })
    },
    // 转化供应商 type 5 转潜在 3 转线索
    async handleConvertSuppliers (data, type) {
      const { supplierId, backlogId } = data
      const { result } = await supplierPreConvertCheck({ supplierId, operateType: type == 5 ? 8 : 5 })
      if (result === '1') {
        if (type === 'qualified') {
          this.$router.push({
            name: 'corventPotential2Qualified',
            query: { id: supplierId, backlogId }
          });
        } else {
          // 潜在转线索
          this.convertType = type
          this.supplier = data
          this.dialogVisible = true
        }
      } else {
        this.$message.error(result)
      }
    },
    // 淘汰供应商
    handleEliminateSuppliers (data, type) {
      console.log(data)
      this.convertType = type
      this.supplier = data
      this.dialogVisible = true
    },
    // 转化供应商提交
    handleDialogSubmit (data) {
      if ((this.convertType === '3' || this.convertType === '5') && data) {
        const { causeType, causeDescription, supplierId, supplierCode, supplierName, backlogId } = data
        const supplierBill = { causeType, causeDescription, supplierId, supplierCode, supplierName, supplierClassify: this.convertType === '3' ? 40899 : 40331 }
        const obj = { processDocumentOperateType: this.convertType === '3' ? 9 : 8, processDocumentStatus: 10, supplierBill, backlogId }
        demoteSupplier(obj).then((resp) => {
          if (resp && resp.status === '0') {
            this.$refs.convertSupplierDialog.close()
            this.$message.success('操作成功！')
          }
        }).finally(() => {
          this.$refs.convertSupplierDialog.updateLoadingState()
        })
        return
      }
      this.dialogVisible = false
    },
    // 关闭弹框
    handleDialogClose () {
      this.dialogVisible = false
    },
    // 跳转资质编辑页
    skipToQualificationEditPage (row) {
      const { supplierClassify, supplierId, backlogId } = row;
      const pathByType = {
        40332: 'editQualifiedSupplier', // 合格供应商
        40331: 'editPotentialSupplier', // 潜在供应商
      }
      this.$router.push({
        name: pathByType[supplierClassify] || '',
        query: { id: supplierId, tab: 5, isReadonlyOtherTabs: 1, disableOtherTabs: 1, backlogId: backlogId }
      });
    },
    // 拉黑供应商
    handleBlackSuppliers (row) {
      this.convertType = '20'
      this.supplier = {
        supplierCode: row.supplierCode,
        supplierId: row.supplierId,
        supplierName: row.supplierName,
        backlogId: row.backlogId
      }
      this.dialogVisible = true
    },
    // 查看审批流
    handleViewApprovalFlow (requestId) {
      // 动态获取工作流跳转地址
      getWorkflowJumpUrl({ requestId }).then(({ result }) => {
        window.open(result, '_blank')
      })
    },
    // 取回单据
    handleWithdraw (row) {
      this.cancelVisable = true;
      this.planData = {
        planCode: row.planCode,
        oaRequestId: row.requestId,
        itemUserId: row.createUserId,
        supplierName: row.supplierName
      }
    },
    // 取消供应商考察报告
    handleCancel (row) {
      this.$confirm('确定取消此报告吗？', '提示', {
        type: 'warning',
      }).then(() => {
        this.cancelInspectReportAction(row)
      }).catch(() => {});
    },
    // 取消供应商考察报告接口调用
    async cancelInspectReportAction (row) {
      const {
        planId,
        id,
        supplierId
      } = row;
      const res = await cancelInspectReportService(
        {
          planId,
          reportId: id,
          supplierId
        },
        state => { this.tableInfo.loading = state }
      )
      if (res) {
        this.$message.success('取消成功')
        this.getTableData()
      }
    },
    // 查看报告评价
    viewReportScroing (row) {
      const { planId, id, supplierId } = row;
      this.$router.push({
        name: 'reportScoringDetail',
        query: { planId, reportId: id, supplierId }
      })
    },
  }
};
</script>
